﻿(function(){
	
	Sateraito = {};
	
	Sateraito.GadgetHeight = {
		
		DEFAULT_GADGET_HEIGHT: 200,
		
		/**
		 * getUserPrefs
		 *
		 * @return {Number} 銈偢銈с儍銉堣ō瀹氥倛銈婅銇裤仩銇椼仧銆屻偓銈搞偋銉冦儓銇珮銇曘€�
		 */
		getUserPrefs: function(aDefaultRetVal)
		{
			var prefs = new gadgets.Prefs();
			var gadgetHeight = parseInt(prefs.getString('gadget_height'), 10);
			alert(gadgetHeight);
			if (isNaN(gadgetHeight)) {
				alert("c");
				if (typeof(aDefaultRetVal) == 'undefined') {
					gadgetHeight = Sateraito.GadgetHeight.DEFAULT_GADGET_HEIGHT;
				} else {
					gadgetHeight = aDefaultRetVal;
				}
			}
							alert("d");

			return gadgetHeight;
		},
		
		/**
		 * setGadgetHeight
		 *
		 * 銈偢銈с儍銉堛伄楂樸仌銈掑啀瑷畾銇欍倠
		 */
		setGadgetHeight: function(){
			gadgets.window.adjustHeight(Sateraito.GadgetHeight.getUserPrefs());
		}
	};
	
	Sateraito.DateUtil = {
		
		dayOfWeek : ['鏃�', '鏈�', '鐏�', '姘�', '鏈�', '閲�', '鍦�'],
		dayOfWeekEn : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],

		/**
		 * timeShorten
		 *
		 * @param {String} aTimeStr HH:MI:SS褰㈠紡
		 * @return {String} HH:MI褰㈠紡
		 */
		timeShorten: function(aTimeStr)
		{
			if (aTimeStr == '') {
				return '';
			}
			
			var timeStrSplited = aTimeStr.split(':');
			return timeStrSplited[0] + ':' + timeStrSplited[1];
		},
		
		/**
		 * shorten
		 *
		 * @param {String} YYYY-MM-DD褰㈠紡
		 * @return {String} M/DD褰㈠紡
		 */
		shorten: function(aDateStr)
		{
			var dateStrSplited = aDateStr.split('-');
//			var vYear = parseInt(dateStrSplited[0], 10);
			var vMonth = parseInt(dateStrSplited[1], 10);
//			var vDay = parseInt(dateStrSplited[2], 10);

			return '' + vMonth + '/' + dateStrSplited[2]
		},
		
		/**
		 * getDayOfWeekStr
		 *
		 * @param {String} aDateStr YYYY-MM-DD褰㈠紡
		 */
		getDayOfWeekStr: function (aDateStr)
		{
			var dateStrSplited = aDateStr.split('-');
			var vYear = parseInt(dateStrSplited[0], 10);
			var vMonth = parseInt(dateStrSplited[1], 10);
			var vDay = parseInt(dateStrSplited[2], 10);
			
			var dateObj = new Date(vYear, vMonth - 1, vDay);
			
			var prefs = new gadgets.Prefs();
			if (prefs.getLang() == 'en' || prefs.getLang() == 'en-gb') {
				return Sateraito.DateUtil.dayOfWeekEn[dateObj.getDay()];
			}
			
			return Sateraito.DateUtil.dayOfWeek[dateObj.getDay()];
		},
		
		/**
		 * checkDate
		 *
		 * @param {Number} aYear
		 * @param {Number} aMonth
		 * @param {Number} aDay
		 */
		checkDate: function(aYear, aMonth, aDay) {
			var dt = new Date(aYear, aMonth - 1, aDay);
			if(dt == null || dt.getFullYear() != aYear || dt.getMonth() + 1 != aMonth || dt.getDate() != aDay) {
				return false;
			}
			return true;
		},
	
		/**
		 * myFormatDate
		 *
		 * 鏃ヤ粯銈儢銈搞偋銈儓銈堛倞銈笺儹浠樸亶銇甕YYY-MM-DD褰㈠紡鏂囧瓧鍒椼倰杩斻仚
		 *
		 * @param {Date} aDate 鏃ヤ粯
		 * @return {String} YYYY-MM-DD褰㈠紡鏂囧瓧鍒�
		 */	
		myFormatDate: function(aDate)
		{
			var yearPart = aDate.getFullYear();
			var monthPart = aDate.getMonth() + 1;
			var dayPart = aDate.getDate();
			
			if (monthPart < 10) monthPart = '0' + monthPart;
			if (dayPart < 10) dayPart = '0' + dayPart;
			
			return '' + yearPart + '-' + monthPart + '-' + dayPart;  
		},
		
		/**
		 * getTodayStr
		 *
		 * @return {String} 鏈棩銇棩浠樻枃瀛楀垪(YYYY-MM-DD)
		 */	
		getTodayStr: function()
		{
			var today = new Date();
			return Sateraito.DateUtil.myFormatDate(today);
		},
		
		/**
		 * formatNumToDate
		 *
		 * @param {Number} aYear
		 * @param {Number} aMonth
		 * @param {Number} aDay
		 */
		formatNumToDate: function(aYear, aMonth, aDay)
		{
			var strYear = '' + aYear;
			var strMonth = '';
			if (aMonth < 10) {
				strMonth = '0' + aMonth;
			} else {
				strMonth = '' + aMonth;
			}
			var strDay = '';
			if (aDay < 10) {
				strDay = '0' + aDay;
			} else {
				strDay = '' + aDay;
			}
			return strYear + '-' + strMonth + '-' + strDay;
		}
	};
	
	Sateraito.Util = {
		
		/**
		 * console
		 */
		console: function(aMsg)
		{
			if (typeof(window.console) != 'undefined') {
				window.console.log(aMsg);
			}
		},
		
		/**
		 * escapeHtml
		 *
		 * @param {String} aStringToEscape
		 */
		escapeHtml: function(aStringToEscape)
		{
			if (aStringToEscape == null) {
				return '';
			}
			if (typeof(aStringToEscape) == 'undefined') {
				return '';
			}
			return aStringToEscape.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
		},
		
		/**
		 * requestParam
		 *
		 * create request parameter to send by makeRequest
		 *
		 * @param {Bool} aIsPost POST銉偗銈ㄣ偣銉堛伀銇欍倠鍫村悎銇痶rue
		 * @param {Object} aPostData POST銇欍倠銉囥兗銈�
		 *
		 * @return obj parameters to send by makeRequest
		 */
		requestParam: function(aIsPost, aPostData)
		{
			if (typeof(aIsPost) == 'undefined') {
				aIsPost = false;
			}
			var param = {};
			param[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
			param[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
			param[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0;
			if (aIsPost) {
				param[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
				param[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(aPostData);
			} else {
				param[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
			}
			return param;
		},

		/**
		 * isMailAddress
		 *
		 * 鏂囧瓧鍒椼亴銉°兗銉偄銉夈儸銈广亱銇┿亞銇嬨倰鍒ゅ畾
		 *
		 * @param {String} aStr
		 * @return {Bool} 鏂囧瓧鍒椼亴銉°兗銉偄銉夈儸銈广伄鍫村悎True
		 */
		isMailAddress: function(aStr)
		{
			var splitedByAtmark = aStr.split('@');
			if (splitedByAtmark.length != 2) {
				return false;
			}
			var splitedByDot = splitedByAtmark[1].split('.');
			if (splitedByDot.length < 2) {
				return false;
			}

			return true;
		},
		
		/**
		 * myBoolToNum
		 *
		 * @param {Bool} aBooleanValue
		 * @return {Number}
		 */
		myBoolToNum: function(aBooleanValue)
		{
			if (aBooleanValue) {
				return 1;
			}
			return 0;
		},
		
		/**
		 * myImplode
		 *
		 * @param {Object} aArray 閰嶅垪
		 * @return {String} 銈兂銉炲尯鍒囥倞銇с儑銉笺偪銈掍甫銇广仧鏂囧瓧鍒�
		 */
		myImplode: function(aArray)
		{
			var retVal = '';
			Ext.each(aArray, function(value, index){
				if (retVal != '') retVal += ',';
				retVal += value;
			});
			return retVal;
		}
	};

	Sateraito.MiniMessage = {
		
		message: null,
		fontSize: 12,
		
		/**
		 * initMessageArea
		 */
		initMessageArea: function(aFontSize)
		{
			var vHtml = '';
			vHtml += '<div id="mini_message" style="position:absolute; top:0px; left:0px; width:200px; text-align:center; z-index:1000;';
			if (typeof(aFontSize) == 'undefined') {
				// no option
			} else {
//				vHtml += 'font-size:' + aFontSize + ';';
				Sateraito.MiniMessage.fontSize = aFontSize;
			}
			vHtml += '"></div>';
			
			// Add Mini Message Area
			$('body').append(vHtml);

			// 銉°儍銈汇兗銈搞伄浣嶇疆銈掑啀閰嶇疆
			var bodyWidth = $(window).width();
			var messageAreaWidth = $('#mini_message').width();
			$('#mini_message').css('left', '' + ((bodyWidth / 2) - (messageAreaWidth / 2)) + 'px');
		},
		
		/**
		 * clearMessage
		 *
		 * 銉°儍銈汇兗銈搞倰娑堝幓銇欍倠
		 */
		clearMessage: function()
		{
			if (Sateraito.MiniMessage.message != null) {
				// 銉°儍銈汇兗銈搞倰娑堛仚
				var prefs = new gadgets.Prefs();
				var msg = new gadgets.MiniMessage(prefs.getModuleId(), $('#mini_message')[0]);
				msg.dismissMessage(Sateraito.MiniMessage.message);
				Sateraito.MiniMessage.message = null;
			}
		},
		
		/**
		 * showTimerMessage
		 *
		 * 鏅傞枔銇屻仧銇ゃ仺娑堛亪銈嬨儭銉冦偦銉笺偢銈掕〃绀�
		 *
		 * @param {String} aMessageText
		 * @param {Number} aTime
		 */
		showTimerMessage: function(aMessageText, aTime)
		{
			if (typeof(aTime) == 'undefined') {
				aTime = 3;
			}
			
			var prefs = new gadgets.Prefs();
			var msg = new gadgets.MiniMessage(prefs.getModuleId(), $('#mini_message')[0]);
			var element = msg.createTimerMessage(aMessageText, aTime);
			element.style.fontSize = '' + Sateraito.MiniMessage.fontSize + 'px';
		},
		
		/**
		 * showLoadingMessage
		 *
		 * @param {String} aMessageText 琛ㄧず銇欍倠瑾伩杈笺伩涓儭銉冦偦銉笺偢锛堢渷鐣ャ仚銈嬨仺銆併儑銉曘偐銉儓銇銇胯炯銇夸腑銉°儍銈汇兗銈搞倰琛ㄧず锛�
		 */
		showLoadingMessage: function(aMessageText)
		{
			var prefs = new gadgets.Prefs();
			
			if (typeof(aMessageText) == 'undefined') {
				aMessageText = prefs.getMsg('LOADING');
			}
			
			Sateraito.MiniMessage.clearMessage();
			
			// 瑾炯涓儭銉冦偦銉笺偢銈掕〃绀�
			var msg = new gadgets.MiniMessage(prefs.getModuleId(), $('#mini_message')[0]);
			Sateraito.MiniMessage.message = msg.createStaticMessage(aMessageText);
			Sateraito.MiniMessage.message.style.fontSize = '' + Sateraito.MiniMessage.fontSize + 'px';
		}
	};
	
	Sateraito.EventController = {
		MAX_RETRY: 10
	};

	Sateraito.GadgetSetting = {
		
		settingName : null,
		settingObj: {},
		mySiteUrl: null,
		
		init: function(aSettingName, aMySiteUrl)
		{
			Sateraito.GadgetSetting.settingName = aSettingName;
			Sateraito.GadgetSetting.mySiteUrl = aMySiteUrl;
		},
		
		/**
		 * requestGetGadgetSetting
		 *
		 * 銈点兗銉愩兗銈点偆銉夈偓銈搞偋銉冦儓銈儍銈兗銈掕銇胯炯銈€
		 *
		 * @param {Function} callback
		 * @param {Number} aNumRetry
		 */
		requestGetGadgetSetting: function(callback, aNumRetry)
		{
			if (typeof(aNumRetry) == 'undefined') {
				aNumRetry = 1;
			}
			
			gadgets.io.makeRequest(Sateraito.GadgetSetting.mySiteUrl + '/getgadgetsetting?setting_name=' + Sateraito.GadgetSetting.settingName, function(response){

				if (!response.data) {

					// response error
					var err = response.errors[0];
					Sateraito.Util.console(err);

					var prefs = new gadgets.Prefs();
					Sateraito.MiniMessage.showTimerMessage(prefs.getMsg('RELOADING') + aNumRetry);
					
					if (aNumRetry < Sateraito.EventController.MAX_RETRY) {
						Sateraito.GadgetSetting.requestGetGadgetSetting(callback, aNumRetry + 1);
					} else {
						// 锛戯紣鍥炪儶銉堛儵銈ゃ仐銇熴亴銇犮倎銇犮仯銇�
						Sateraito.MiniMessage.showTimerMessage(prefs.getMsg('ERROR_WHILE_LOADING'), 10);
					}

					return;
				}

				var jsondata = response.data;

				if (jsondata.is_error) {
					// 銈ㄣ儵銉�
					Sateraito.Util.console(jsondata.error_code);
					callback(null);
				} else {
					Sateraito.GadgetSetting.settingObj = gadgets.json.parse(decodeURI(jsondata.setting_value));
					callback(Sateraito.GadgetSetting.settingObj);
				}

			}, Sateraito.Util.requestParam());
		},
		
		/**
		 * requestSetGadgetSetting
		 *
		 * 銈点兗銉愩兗銈点偆銉夈偓銈搞偋銉冦儓銈儍銈兗銈掍繚瀛樸仚銈�
		 *
		 * @param {Object} aSettingObj
		 * @param {Function} callback
		 * @param {Number} aNumRetry
		 */
		requestSetGadgetSetting: function(aSettingObj, callback, aNumRetry)
		{
			if (typeof(aNumRetry) == 'undefined') {
				aNumRetry = 1;
			}
			
			var settingValue = encodeURI(gadgets.json.stringify(aSettingObj));
			
			var postData = {
				'setting_name': Sateraito.GadgetSetting.settingName,
				'setting_value': settingValue
			};
			
			gadgets.io.makeRequest(Sateraito.GadgetSetting.mySiteUrl + '/setgadgetsetting', function(response){

				if (!response.data) {

					// response error
					var err = response.errors[0];

					var prefs = new gadgets.Prefs();
					Sateraito.MiniMessage.showTimerMessage(prefs.getMsg('RELOADING') + aNumRetry);
					
					if (aNumRetry < Sateraito.EventController.MAX_RETRY) {
						Sateraito.GadgetSetting.requestSetGadgetSetting(aSettingObj, callback, (aNumRetry + 1));
					} else {
						// 锛戯紣鍥炪儶銉堛儵銈ゃ仐銇熴亴銇犮倎銇犮仯銇�
						Sateraito.MiniMessage.showTimerMessage(prefs.getMsg('ERROR_WHILE_LOADING'), 10);
					}

					return;
				}

				var jsondata = response.data;
				callback();
				
			}, Sateraito.Util.requestParam(true, postData));
		}
	};
	
})();